#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Wed Jul 10 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
from datetime import datetime, timedelta
from .base import BaseHandler


class OnlineHandler(BaseHandler):

    def __init__(self, *args, **kwargs):
        self.last_post_time_map = {}
        return super().__init__(*args, **kwargs)

    def handle(self, msg):
        device_id = msg['deviceId']
        # 如果不在添加车辆的最后时间 同时向后端添加第一条数据
        vehicle_id = self.not_exist_add_vehicle(device_id)

        if device_id not in self.last_post_time_map:
            self.last_post_time_map[device_id] = datetime.now()

        # 每接近一分钟更新一次车辆状态
        if self.last_post_time_map[device_id] + timedelta(seconds=100) < datetime.now():
            data = {
                "status": "ONLINE" if msg['online'] else "OFFLINE",
                "last_time": self.timespan2str(msg['time'])
            }
            self.last_post_time_map[device_id] = datetime.now()
            return self.yb_api.update_vehicle_status(vehicle_id, data)
